package com.example.udpdemo.controller;

import com.example.udpdemo.service.UDPClientService;
import com.example.udpdemo.service.UDPServerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * UDP控制器
 * 提供HTTP接口来测试UDP功能
 * 
 * @author demo
 */
@RestController
@RequestMapping("/api/udp")
public class UDPController {

    private static final Logger log = LoggerFactory.getLogger(UDPController.class);

    @Autowired
    private UDPServerService udpServerService;

    @Autowired
    private UDPClientService udpClientService;

    /**
     * 获取UDP服务器状态
     */
    @GetMapping("/status")
    public Map<String, Object> getServerStatus() {
        log.info("获取UDP服务器状态");
        
        Map<String, Object> result = new HashMap<>();
        result.put("serverStatus", udpServerService.getServerStatus());
        result.put("serverRunning", udpServerService.isRunning());
        result.put("serverReceivedCount", udpServerService.getReceivedCount());
        result.put("serverSentCount", udpServerService.getSentCount());
        result.put("clientSentCount", udpClientService.getSentCount());
        result.put("clientReceivedCount", udpClientService.getReceivedCount());
        result.put("timestamp", System.currentTimeMillis());
        
        return result;
    }

    /**
     * 发送UDP消息
     */
    @PostMapping("/send")
    public Map<String, Object> sendMessage(@RequestBody Map<String, Object> request) {
        String targetHost = (String) request.getOrDefault("host", "localhost");
        Integer targetPort = (Integer) request.getOrDefault("port", 8888);
        String message = (String) request.getOrDefault("message", "Hello UDP!");
        Boolean waitResponse = (Boolean) request.getOrDefault("waitResponse", false);
        Integer timeout = (Integer) request.getOrDefault("timeout", 5000);
        
        log.info("发送UDP消息: {}:{} - {}", targetHost, targetPort, message);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (waitResponse) {
                // 发送消息并等待响应
                String response = udpClientService.sendMessageWithResponse(targetHost, targetPort, message, timeout);
                result.put("success", true);
                result.put("response", response);
                result.put("message", "消息发送成功并收到响应");
            } else {
                // 发送消息（不等待响应）
                boolean success = udpClientService.sendMessage(targetHost, targetPort, message);
                result.put("success", success);
                result.put("message", success ? "消息发送成功" : "消息发送失败");
            }
            
            result.put("targetHost", targetHost);
            result.put("targetPort", targetPort);
            result.put("sentMessage", message);
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("发送UDP消息时发生异常", e);
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("message", "发送消息时发生异常");
        }
        
        return result;
    }

    /**
     * 广播UDP消息
     */
    @PostMapping("/broadcast")
    public Map<String, Object> broadcastMessage(@RequestBody Map<String, Object> request) {
        Integer targetPort = (Integer) request.getOrDefault("port", 8888);
        String message = (String) request.getOrDefault("message", "Hello UDP Broadcast!");
        
        log.info("广播UDP消息: {}:{} - {}", "255.255.255.255", targetPort, message);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = udpClientService.broadcastMessage(message, targetPort);
            result.put("success", success);
            result.put("message", success ? "广播消息发送成功" : "广播消息发送失败");
            result.put("broadcastAddress", "255.255.255.255");
            result.put("targetPort", targetPort);
            result.put("sentMessage", message);
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("广播UDP消息时发生异常", e);
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("message", "广播消息时发生异常");
        }
        
        return result;
    }

    /**
     * 重置计数器
     */
    @PostMapping("/reset")
    public Map<String, Object> resetCounters() {
        log.info("重置UDP计数器");
        
        udpClientService.resetCounters();
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "计数器已重置");
        result.put("timestamp", System.currentTimeMillis());
        
        return result;
    }

    /**
     * 测试本地UDP通信
     */
    @PostMapping("/test")
    public Map<String, Object> testLocalUDP() {
        log.info("测试本地UDP通信");
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 发送测试消息到本地UDP服务器
            String response = udpClientService.sendMessageWithResponse("localhost", 8888, "测试消息", 3000);
            
            result.put("success", true);
            result.put("response", response);
            result.put("message", "本地UDP通信测试成功");
            result.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("测试本地UDP通信时发生异常", e);
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("message", "本地UDP通信测试失败");
        }
        
        return result;
    }

    /**
     * 简单的Hello接口
     */
    @GetMapping("/hello")
    public Map<String, Object> hello() {
        Map<String, Object> result = new HashMap<>();
        result.put("message", "Hello UDP Demo!");
        result.put("serverStatus", udpServerService.getServerStatus());
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }
} 